﻿using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
using Microsoft.Extensions.Logging;
using NlpApp.Model;
using System.Text;
using System.Threading.Tasks;

namespace NlpApp.Webapi.Middlewares
{
    /// <summary>
    /// http全局错误处理 使用方式 services.AddControllers(options =>options.Filters.Add(new HttpResponseExceptionFilter()));
    /// </summary>
    #region snippet_HttpResponseExceptionFilter
    public class HttpResponseExceptionFilter : IAsyncExceptionFilter
    {
        private readonly ILogger<HttpResponseExceptionFilter> logger;
        /// <summary>
        /// Initializes a new instance of the <see cref="HttpResponseExceptionFilter"/> class.
        /// </summary>
        /// <param name="logger">The logger.</param>
        public HttpResponseExceptionFilter(ILogger<HttpResponseExceptionFilter> logger)
        {
            this.logger = logger;
        }
        /// <summary>
        /// 重写OnExceptionAsync方法，定义自己的处理逻辑 app.UseExceptionHandler(builder => builder.Use(HttpResponseExceptionMiddleware.ExceptionHandler));
        /// </summary>
        /// <param name="context"></param>
        /// <returns></returns>
        public async Task OnExceptionAsync(ExceptionContext context)
        {
            // 如果异常没有被处理则进行处理
            if (!context.ExceptionHandled)
            {
                var ex = context.Exception;
                StringBuilder stringBuilder = new StringBuilder();
                stringBuilder.AppendLine(ex.Message);
                logger.LogError(ex, "异常信息：{0}", ex.Message);
                context.Result = new JsonResult(new HttpReturnEntity { Code = "1", Message = stringBuilder.ToString() });
                context.ExceptionHandled = true;
            }
            await Task.CompletedTask;
        }
    }
    #endregion
}
